package com.pureut.quality.scheduling;

import com.pureut.quality.domain.QualityInspectionManagement;
import com.pureut.quality.mapper.QualityInspectionManagementMapper;
import com.pureut.quality.service.QualityInspectionManagementService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/***
 * 免检管理定时器
 * Author:C
 * Date:2023/02/03 16:55
 * @DESC
 */
@Component
public class QualityInspectionManagementScheduling {

    @Resource
    QualityInspectionManagementService qualityInspectionManagementService;


    //校验时间区间修改免检管理状态
    @Scheduled(cron = "0 0 0 * * ?")
    public void modifyStatusAccordingToTime() throws ParseException {

        //获取免检管理列表
        List<QualityInspectionManagement> list = qualityInspectionManagementService.list();

        List<QualityInspectionManagement> qualityInspectionManagementList = new ArrayList<>();
        for (QualityInspectionManagement entity : list) {
            if (entity.getReviewStatus() == 2 && entity.getStatus() == 1) {
                //判断当前时间是否在有效时间之内
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(new Date());
                Date nowTime;
                nowTime = sdf.parse(format);
                Date validityStartTime = entity.getValidityStartTime();
                Date validityEndTime = entity.getValidityEndTime();
                boolean trueTime = isTrueTime(nowTime, validityStartTime, validityEndTime);
                if (!trueTime) {
                    entity.setStatus(2);
                    entity.setReviewStatus(5);
                }
                qualityInspectionManagementList.add(entity);
            }
        }
        qualityInspectionManagementService.updateBatchById(qualityInspectionManagementList);
    }

    /**
     * 判断当前时间是否在某个时间区间
     */
    public boolean isTrueTime(Date nowTime, Date startTime, Date endTime) {

        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }
}
